<template>
  <el-drawer
    v-model="drawerVisible"
    :destroy-on-close="true"
    size="700px"
    :title="`${drawerProps?.title}菜单`"
    @open="drawerOpen"
  >
    <el-form ref="menuRef" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="上级菜单">
            <el-tree-select
              v-model="form.parentId"
              :data="menuOptions"
              :props="{ value: 'menuId', label: 'menuName', children: 'children' }"
              value-key="id"
              placeholder="选择上级菜单"
              clearable
              check-strictly
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="菜单类型" prop="type">
            <el-radio-group v-model="form.menuType">
              <el-radio label="M">目录</el-radio>
              <el-radio label="C">菜单</el-radio>
              <el-radio label="F">按钮</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜单名称" prop="menuName">
            <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="英文名称" prop="enName">
            <el-input v-model="form.enName" placeholder="请输入菜单英文名称" />
          </el-form-item>
        </el-col> -->
        <el-col v-if="form.menuType != 'F'" :span="12">
          <el-form-item label="菜单图标" prop="icon">
            <SelectIcon :slot-position="'prepend'" v-model:icon-value="form.icon" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="显示排序" prop="orderNum">
            <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>

        <el-col v-if="form.menuType != 'F'" :span="12">
          <el-form-item>
            <template #label>
              <span>路由Name</span>
            </template>
            <el-input v-model="form.routeName" placeholder="请输入路由name" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.menuType != 'F'" :span="12">
          <el-form-item prop="path">
            <template #label>
              <span> 路由Path </span>
            </template>
            <el-input v-model="form.path" placeholder="请输入路由地址" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.menuType == 'M'" :span="24">
          <el-form-item prop="redirectUrl">
            <template #label>
              <span> 路由重定向</span>
            </template>
            <el-input v-model="form.redirectUrl" placeholder="请输入路由重定向地址" />
          </el-form-item>
        </el-col>

        <el-col v-if="form.menuType == 'C'" :span="12">
          <el-form-item prop="component">
            <template #label>
              <span>
                <el-tooltip content="访问的组件路径，如：`/system/user/index`，默认在`views`目录下" placement="top">
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
                组件路径
              </span>
            </template>
            <el-input v-model="form.component" placeholder="请输入组件路径" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.menuType == 'C'" :span="12">
          <el-form-item>
            <el-input v-model="form.query" placeholder="请输入路由参数" maxlength="255" />
            <template #label>
              <span>
                <el-tooltip content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`' placement="top">
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
                路由参数
              </span>
            </template>
          </el-form-item>
        </el-col>
        <el-col v-if="form.menuType != 'M'" :span="12">
          <el-form-item>
            <el-input v-model="form.perms" placeholder="请输入权限标识" maxlength="100" />
            <template #label>
              <span>
                <el-tooltip
                  content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                  placement="top"
                >
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
                权限字符
              </span>
            </template>
          </el-form-item>
        </el-col>
        <el-col v-if="form.menuType == 'C'" :span="12">
          <el-form-item>
            <template #label>
              <span>
                <span>是否外链</span>
              </span>
            </template>
            <el-radio-group v-model="form.isFrame">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <template v-if="form.isFrame == 1">
          <el-col v-if="form.menuType == 'C'" :span="12">
            <el-form-item>
              <template #label>
                <span>
                  <el-tooltip content="外链则路由地址需要以`http(s)://`开头" placement="top">
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  外链地址
                </span>
              </template>
              <el-input v-model="form.linkHref" placeholder="请输入外链地址，以http(s)://`开头" />
            </el-form-item>
          </el-col>
        </template>

        <el-col v-if="form.menuType == 'C'" :span="12">
          <el-form-item>
            <template #label>
              <span>
                <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和路由name保持一致" placement="top">
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
                是否缓存
              </span>
            </template>
            <el-radio-group v-model="form.isCache">
              <el-radio :label="1">缓存</el-radio>
              <el-radio :label="0">不缓存</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.menuType == 'C'" :span="12">
          <el-form-item>
            <template #label>
              <span>
                <el-tooltip content="全屏时，则不显示layout,页面内容为全屏状态，适用于BI大屏展示" placement="top">
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
                是否全屏
              </span>
            </template>
            <el-radio-group v-model="form.isFull">
              <el-radio :label="0">不全屏</el-radio>
              <el-radio :label="1">全屏</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.menuType != 'F'" :span="12">
          <el-form-item>
            <template #label>
              <span>
                <el-tooltip content="选择禁用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
                菜单状态
              </span>
            </template>
            <el-radio-group v-model="form.status">
              <el-radio :label="0">启用</el-radio>
              <el-radio :label="1">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.menuType != 'F'" :span="12">
          <el-form-item>
            <template #label>
              <span>
                <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
                显示状态
              </span>
            </template>
            <el-radio-group v-model="form.visible">
              <el-radio :label="1">显示</el-radio>
              <el-radio :label="0">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.menuType == 'C' && form.visible == 0" :span="12">
          <el-form-item>
            <template #label>
              <span> 高亮路由 </span>
            </template>
            <el-input v-model="form.activeMenu" placeholder="请输入高亮路由path" maxlength="255" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false"> 取消 </el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="MenuDrawer">
import { ref, reactive, toRefs, getCurrentInstance, ComponentInternalInstance } from "vue";
import SelectIcon from "@/components/SelectIcon/index.vue";
import { ElMessage, FormInstance } from "element-plus";
import { handleTree } from "@/utils";
import { MenuApi } from "@/api/modules";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Menu.MenuOptions>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}
const menuOptions = ref<any[]>([]);
const drawerVisible = ref(false);
const showChooseIcon = ref(false);
const iconSelectRef = ref<any>(null);
const data = reactive<{
  form: any;
  queryParams: any;
  rules: any;
}>({
  form: {
    menuType: "C", // 1 目录，2菜单，3按钮
    menuName: "", // 菜单名称
    enName: undefined, // 英文菜单名称 ''
    routeName: "", //路由name ''
    icon: "Menu", //菜单图标
    orderNum: 1, //排序
    isFrame: 0, //是否为外链 0
    isBlank: true,
    linkHref: undefined,
    path: "", // 路由地址
    component: undefined, // 组件路径
    redirectUrl: undefined, // 跳转地址 null
    perms: undefined, //权限字段
    isFull: 0, // 是否全屏 0
    isCache: 1, // 是否缓存 1缓存 0 不缓存
    visible: 1, // 是否可见  1可见 0 不可见
    activeMenu: undefined, // 高亮菜单 // visible 为false时需要
    status: 0, // 状态 1 正常 0 禁用
  },
  queryParams: {
    menuName: undefined,
    visible: undefined,
  },
  rules: {
    menuName: [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
    orderNum: [{ required: true, message: "菜单顺序不能为空", trigger: "blur" }],
    path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }],
  },
});
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {},
});
const { queryParams, form, rules } = toRefs(data);

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  if (params.row) {
    if (params.title == "编辑") {
      data.form = JSON.parse(JSON.stringify(params.row));
    }
    if (params.title == "新增") {
      (data.form = {
        parentId: 0,
        menuType: "C", // 1 目录，2菜单，3按钮
        menuName: "", // 菜单名称
        routeName: "", //路由name ''
        icon: "Menu", //菜单图标
        orderNum: 1, //排序
        isFrame: 0, //是否为外链 0
        linkHref: undefined,
        isBlank: true,
        path: "", // 路由地址
        component: undefined, // 组件路径
        redirectUrl: undefined, // 跳转地址 null
        perms: undefined, //权限字段
        isFull: 0, // 是否全屏 0
        isCache: 1, // 是否缓存 1
        visible: 1, // 是否可见  0:可见，
        activeMenu: undefined, // 高亮菜单 // visible 为false时需要
        status: 0, // 状态 0正常 1停用
      }),
        (data.form.parentId = params.row.id);
    }
  }
  drawerVisible.value = true;
};
// drawer 打开时的事件
const drawerOpen = () => {
  getTreeSelect();
};
// 提交数据（新增/编辑）

const handleSubmit = () => {
  (proxy?.$refs["menuRef"] as any).validate(async (valid: any) => {
    if (!valid) return;
    try {
      const menuData = JSON.parse(JSON.stringify(data.form));
      if (!menuData.parentId) {
        menuData.parentId = 0;
      }
      if (menuData.menuId) {
        await MenuApi.editMenu(menuData);
      } else {
        await MenuApi.addMenu(menuData);
      }
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerVisible.value = false;
      drawerProps.value.getTableList!();
    } catch (error) {
      console.log(error);
    }
  });

  // ruleFormRef.value!.validate(async valid => {
  //   if (!valid) return;
  //   try {
  //     await drawerProps.value.api!(drawerProps.value.row);
  //     ElMessage.success({ message: `${drawerProps.value.title}用户成功！` });
  //     drawerProps.value.getTableList!();
  //     drawerVisible.value = false;
  //   } catch (error) {
  //     console.log(error);
  //   }
  // });
};
const getTreeSelect = () => {
  menuOptions.value = [];
  MenuApi.getMenuList({}).then((response: any) => {
    let filterMenu = response.data.filter(item => item.menuType != "F");
    const menu = handleTree(filterMenu, "menuId");
    const data = [
      {
        menuId: 0,
        menuName: "根类目",
        children: menu,
      },
    ];
    menuOptions.value = data;
  });
};

defineExpose({
  acceptParams,
});
</script>
